package com.heima.example.chat.server.handler;

import com.heima.example.chat.message.GroupCreateRequestMessage;
import com.heima.example.chat.message.GroupCreateResponseMessage;
import com.heima.example.chat.server.session.Group;
import com.heima.example.chat.server.session.GroupSession;
import com.heima.example.chat.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 创建群聊
 * @author ZhengDp
 * @Date 2023/6/30 21:13
 */
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        Set<String> memebers = msg.getMembers();
        // 群管理器
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(groupName, memebers);
        if(Objects.isNull(group)) {
            // 创建成功
            ctx.writeAndFlush(new GroupCreateResponseMessage(true,groupName + "创建成功"));
            // 发送拉群消息
            List<Channel> channels = groupSession.getMembersChannel(groupName);
            for(Channel channel : channels) {
                channel.writeAndFlush(new GroupCreateResponseMessage(true,"您已被拉入" + groupName + "群组"));
            }
        } else {
            // 已经存在
            ctx.writeAndFlush(new GroupCreateResponseMessage(false,groupName + "已经存在"));
        }
    }
}
